import { Input, NavBar } from 'antd-mobile'
import classnames from 'classnames'
import { useHistory } from 'react-router-dom'
import Icon from '@/components/Icon'
import styles from './index.module.scss'
// 聊天
import { io, Socket } from 'socket.io-client'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'
import { RootState } from '@/types/store'

type Chat = {
  message: string
  type: 'user' | 'xz'
}

const Chats = () => {
  const history = useHistory()
  // 聊天
  // 列表
  const [chatList, setChatList] = useState<Chat[]>([])
  // 聊天内容
  const [value, setValue] = useState('')
  const socketRef = useRef<Socket>()
  // 获取用户
  const { photo } = useSelector((state: RootState) => state.profile.user)

  useEffect(() => {
    // 1 建立连接
    const socketio = io('http://toutiao.itheima.net', {
      // 参数
      query: {
        token: '',
      },
      // 连接方式
      transports: ['websocket'],
    })
    // 存储io实例
    socketRef.current = socketio

    // 2 连接成功
    socketio.on('connect', () => {
      console.log('websocket 连接成功')
      // 让小智给你打个招呼
      setChatList([
        { message: '你好，我是小智', type: 'xz' },
        { message: '你有什么疑问？', type: 'xz' },
      ])
    })

    // 3. 接收服务器返回的消息
    socketio.on('message', (data) => {
      setChatList((list) => [
        ...list,
        {
          message: data.msg,
          type: 'xz',
        },
      ])
    })

    return () => {
      socketio.close()
    }
  }, [])

  // 4. 发送消息
  const onSendMsg = () => {
    if (!value.trim()) return

    // 发送消息给服务器
    socketRef.current?.emit('message', {
      msg: value,
      timestamp: Date.now() + '',
    })

    setChatList([
      ...chatList,
      {
        type: 'user',
        message: value,
      },
    ])

    setValue('')
  }

  // 聊天内容滚动展示
  const chatListRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    const chatListDOM = chatListRef.current
    if (!chatListDOM) return

    chatListDOM.scrollTop = chatListDOM.scrollHeight
  }, [chatList])

  return (
    <div className={styles.root}>
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      <div className="chat-list" ref={chatListRef}>
        {/* <div className={classnames('chat-item', true ? 'self' : 'user')}>
          {true ? (
            <Icon type="iconbtn_xiaozhitongxue" />
          ) : (
            <img src="http://geek.itheima.net/images/user_head.jpg" alt="" />
          )}
          <div className="message">你好，我是小智</div>
        </div> */}
        {chatList.map((item, index) => {
          return (
            <div
              key={index}
              className={classnames(
                'chat-item',
                item.type === 'xz' ? 'self' : 'user'
              )}>
              {item.type === 'xz' ? (
                <Icon type="iconbtn_xiaozhitongxue" />
              ) : (
                <img
                  // src="http://geek.itheima.net/images/user_head.jpg"
                  src={photo}
                  alt=""
                />
              )}
              <div className="message">{item.message}</div>
            </div>
          )
        })}
      </div>

      <div className="input-footer">
        <Input
          className="no-border"
          placeholder="请描述您的问题"
          value={value}
          onChange={(value) => setValue(value)}
          onEnterPress={onSendMsg}
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chats
